﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace SCFHS.Views.Reports
{
    public partial class OrderByNumber : SysBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (!string.IsNullOrEmpty(txtOrderNumber.Text))
                {
                    BindReport(txtOrderNumber.Text);
                    return;
                }
            }
            if (Request.QueryString["orderId"] != null && !IsPostBack)
            {
                string orderID = Request.QueryString["orderId"].ToString();
                if (!string.IsNullOrEmpty(orderID))
                {
                    txtOrderNumber.Text = orderID;
                    BindReport(orderID);
                }
            }
        }

        protected void btnShowReport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtOrderNumber.Text))
                Response.Redirect("OrderByNumber.aspx?orderId=" + txtOrderNumber.Text);
        }

        DataTable HandleHeaderColumn(DataTable dt, string headerText)
        {
            DataColumn dc = new DataColumn("DetailHeader");
            dc.DefaultValue = headerText;
            dt.Columns.Add(dc);
            dc = new DataColumn("Indexer");
            dt.Columns.Add(dc);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["Indexer"] = (i + 1).ToString();
            }
            return dt;
        }

        void BindReport(string orderNumber)
        {
            rptViewer.ID = "Report Number " + orderNumber + "";
            DataTable orderDt = null;
            if (Session["orderData"] != null)
            {
                orderDt = Session["orderData"] as DataTable;
                if (orderDt.Rows[0]["OrderNumber"].ToString() != orderNumber)
                {
                    orderDt = null;
                }
            }

            if (orderDt == null)
            {
                orderDt = controller.SelectFullOrderDetailsInfo(orderNumber);

                if (orderDt == null)
                    return;
                if (orderDt.Rows[0]["OrderState"].ToString() != ((int)Code.OrderStates.Place).ToString())
                {
                    lblMessage.Text = Messages.ProceudProcessField;
                    lblMessage.CssClass = "error";
                    return;
                }
                int orderID = (int)orderDt.Rows[0][0];
                DataTable subDt = controller.ListFullSummeryPointsForOrder(orderID);
                if (subDt != null)
                    orderDt.Merge(HandleHeaderColumn(subDt, Messages.ReportTitleSummery), false);
                subDt = null;
                subDt = controller.ListFullRequestPointsForOrder(orderID);
                if (subDt != null)
                    orderDt.Merge(HandleHeaderColumn(subDt, Messages.ReportTitleRequest));
                subDt = null;
                subDt = controller.ListAttachmentPoints(orderID);
                if (subDt != null)
                    orderDt.Merge(HandleHeaderColumn(subDt, Messages.ReportTitleAttachments));
                //Clear data
                orderDt = ClearDetailsStyle(orderDt);
                BindRpt(orderDt);
            }



        }

        ReportDocument report;

        void BindRpt(DataTable orderDtSrc)
        {
            rptViewer.ReportSource = new ReportDocument();

            if (orderDtSrc != null)
            {
                ParameterFields rptParams = new ParameterFields();
                
                rptParams.Add(HandleRptParams("CompletedBy", orderDtSrc.Rows[0]["CompletedBy"].ToString()));
                rptParams.Add(HandleRptParams("OrderCompletedOn", orderDtSrc.Rows[0]["OrderCompletedOn"].ToString()));

                rptViewer.Visible = true;
                report = new ReportDocument();
                report.Load(Server.MapPath("Design/FullOrder.rpt"));
                report.SetDataSource(orderDtSrc);
                report.SummaryInfo.ReportTitle = "طلب رقم " + orderDtSrc.Rows[0]["OrderNumber"].ToString() + "";
                rptViewer.ReportSource = report;
                rptViewer.ParameterFieldInfo = rptParams;
                hdfOrderNumber.Value = orderDtSrc.Rows[0]["ID"].ToString();
                btnToInstructions.Visible = true;
                rptViewer.DataBind();

            }
            else
            {
                lblMessage.Text = "عفوا لا يوجد بيانات لهذا الطلب";
                lblMessage.CssClass = "error";
            }
        }

        private DataTable ClearDetailsStyle(DataTable orderDt)
        {
            for (int i = 1; i < orderDt.Rows.Count; i++)
            {
                orderDt.Rows[i - 1]["DetailHeader"] = orderDt.Rows[i]["DetailHeader"];
                orderDt.Rows[i - 1]["Indexer"] = orderDt.Rows[i]["Indexer"];
                orderDt.Rows[i - 1]["Point"] = orderDt.Rows[i]["Point"];
                orderDt.Rows[i - 1]["Fk_OrderID"] = orderDt.Rows[i]["Fk_OrderID"];
            }
            orderDt.Rows.RemoveAt(orderDt.Rows.Count - 1);
            return orderDt;
        }

        private ParameterField HandleRptParams(string name, string value)
        {
            ParameterDiscreteValue rptDiscreteVal = new ParameterDiscreteValue();
            ParameterField rptParam = new ParameterField();

            rptDiscreteVal.Value = value;
            rptParam.Name = name;
            rptParam.CurrentValues.Add(rptDiscreteVal);

            return rptParam;
        }


        protected void Page_Unload(object sender, EventArgs e)
        {
            ReportDocument report = rptViewer.ReportSource as ReportDocument;
            rptViewer.ReportSource = null;
            if (report == null)
                return;
            report.Database.Dispose();
            report.Close();
            report.Dispose();
            GC.Collect();

        }

        protected void btnToInstructions_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdfOrderNumber.Value))
            {
                lblMessage.Text = Messages.UpdateOrderFail;
                lblMessage.CssClass = "error";
                return;
            }
            try
            {
                bool result = controller.UpdateOrderStates(int.Parse(hdfOrderNumber.Value), Code.OrderStates.Printed, user.userID);
                if (result)
                {
                    txtOrderNumber.Text = "";
                    lblMessage.Text = Messages.UpdateOrderSuccess;
                    lblMessage.CssClass = "info";
                    rptViewer.Visible = false;
                    btnToInstructions.Visible = false;
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}